﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Core.Extensions;
using App.Domain;
using App.Web.ViewModels;
using App.Web.Utility;
using AutoMapper;
using System.Web.Script.Serialization;

namespace App.Web.Controllers
{
    public class AjaxController : BaseController
    {
		private AppEntities _Context = new AppEntities();
        
		#region Constructors
		public AjaxController()
		{
		}

		public AjaxController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        [HttpPost]
        public String AddProductToCompare(int productID)
        {
            Product product = _Context.Products.Include("ProductImages").FirstOrDefault(P => P.ID == productID);
            if (product != null)
            {
                ProductViewModel viewModel = new ProductViewModel();
                viewModel.ID = product.ID;
                viewModel.ProductUrl = product.ProductUrl;
                viewModel.Name = product.Name;
                if (product.ProductImages != null && product.ProductImages.Count > 0)
                {
                    viewModel.ProductImages = new List<ProductImageViewModel>();
                    ProductImageViewModel image = Mapper.Map<ProductImageViewModel>(product.ProductImages.ToList()[0]);
                    viewModel.ProductImages.Add(image);                    
                }
                List<ProductViewModel> storedList = SessionCache.ProductCompareList;
                if (storedList.Count < ConfigReader.MaxNoOfProductsCanBeCompare 
                    && storedList.FirstOrDefault(P => P.ID == productID) == null)
                {
                    storedList.Add(viewModel);
                    SessionCache.ProductCompareList = storedList;
                    return viewModel.ToJSON();
                }
            }
            return String.Empty;
        }

        /// <summary>
        /// Deletes a Product from the Session
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        [HttpPost]
        public int RemoveProductToCompare(int productID)
        {
            List<ProductViewModel> storedList = SessionCache.ProductCompareList;
            ProductViewModel product = storedList.FirstOrDefault(P => P.ID == productID);
            if (product != null)
            {
                storedList.Remove(product);
                SessionCache.ProductCompareList = storedList;
                return 1;
            }
            return 0;
        }
		#endregion Action Methods
		
		#region Helper Methods

        #endregion			
    }
}
